<template>
    <BasicInformation :title="title" @action="handleAction" :primary-actions="mainActions"></BasicInformation>
    <div class="add">
       <div class="common-layout">
         <el-container>
           <el-main>
             <el-row>
               <el-col :span="24">
                 <div class="grid-content ep-bg-purple">
                   <h4>基本信息</h4>
                   <el-form :inline="true" :model="salesCollection" :rules="rules" status-icon ref="formRef">
                     <el-form-item label="单据编号" prop="docCode">
                     <el-input 
                     v-model="salesCollection.docCode"
                     style="width: 240px"
                     placeholder="请输入单据编号"
                     clearable
                     :disabled="true"
                     />
                   </el-form-item>
                     <!-- 客户 -->
                     <el-form-item label="客户" prop="cid">
                             <el-select
                               v-model="salesCollection.cid" 
                               placeholder="请选择客户"
                               style="width: 240px"
                               clearable
                               filterable
                             >
                               <el-option
                                 v-for="customer in customerList"
                                 :key="customer.id"
                                 :label="`${customer.code} - ${customer.name}`"
                                 :value="customer.id"
                               />
                             </el-select>
                           </el-form-item>
 
                     <!-- 报价日期 -->
                     <el-form-item label="单据日期" prop="docDate">
                       <el-date-picker
                         v-model="salesCollection.docDate"
                         type="date"
                         placeholder="请选择日期"
                         value-format="YYYY-MM-DD"
                         :disabled-date="disabledDate"
                       />
                     </el-form-item>
                     <!-- 业务员 -->
                                        <el-form-item label="业务员" prop="uid">
                                            <el-select v-model="salesCollection.uid" placeholder="请选择业务员" clearable filterable @change="" style="width: 240px;">
                                            <el-option v-for="item in userList"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id">
                                            </el-option>
                                            </el-select>                                                                     
                                        </el-form-item>

                                        <!-- 部门 -->
                                        <el-form-item label="部门" prop="did">
                                            <el-select
                                                v-model="salesCollection.did"
                                                placeholder="请选择部门"
                                                style="width: 240px;"
                                                clearable
                                            >
                                                <el-option
                                                    v-for="dept in deptList"
                                                    :key="dept.id"
                                                    :label="dept.name"
                                                    :value="dept.id"
                                                />
                                            </el-select>
                                        </el-form-item>

                                        <el-form-item label="单据备注" prop="notes">
                                                <el-input 
                                                v-model="salesCollection.notes"
                                                style="width: 240px"
                                                placeholder="请输入单据备注"
                                                clearable
                                                />
                                        </el-form-item>

                          </el-form>
                 </div>
               </el-col>
             </el-row>
           </el-main>
         </el-container>
       </div>
     </div>
   <!-- 收款信息表格 -->
  <div class="collection-info">
    <h4>收款信息</h4>
    <el-table :data="paymentAccounts" border style="width: 100%">
      <el-table-column label="收款账户" align="center" width="150">
        <template #default="scope">
          <el-select 
            v-model="scope.row.accountName" 
            placeholder="请选择账户"
            clearable
          >
            <el-option
              v-for="account in payAccountList"
              :key="account.id"
              :label="account.account"
              :value="account.id"
            />
          </el-select>
        </template>
      </el-table-column>
      
      <el-table-column label="收款方式" align="center" width="150">
        <template #default="scope">
          <el-select 
            v-model="scope.row.payId" 
            placeholder="请选择方式"
            clearable
          >
            <el-option
              v-for="method in payIdList"
              :key="method.id"
              :label="method.payName"
              :value="method.id"
            />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="收款金额" align="center" width="180">
        <template #default="scope">
          <el-input-number 
            v-model="scope.row.amount" 
            :min="0" 
            :precision="2"
            controls-position="right"
            style="width: 160px"
            @change="handlePaymentChange(scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column label="手续费" align="center" width="150">
        <template #default="scope">
          <el-input-number 
            v-model="scope.row.fee" 
            :min="0" 
            :precision="2"
            controls-position="right"
            style="width: 120px"
          />
        </template>
      </el-table-column>

      <el-table-column label="交易号/票据号" align="center">
        <template #default="scope">
          <el-input 
            v-model="scope.row.transactionNo" 
            placeholder="请输入交易号"
            clearable
          />
        </template>
      </el-table-column>

      <el-table-column label="收款备注" align="center">
        <template #default="scope">
          <el-input 
            v-model="scope.row.notes" 
            placeholder="请输入备注"
            clearable
          />
        </template>
      </el-table-column>
    </el-table>
    <div class="validation-info">
    <el-alert 
      v-if="netCollectionAmount > maxSettleAmount"
      type="error" 
      :closable="false"
      show-icon
    >
      超额收款！可核销上限：¥{{ maxSettleAmount.toFixed(2) }}
    </el-alert>
    
    <div class="amount-summary">
      <span>净收款金额：¥{{ netCollectionAmount.toFixed(2) }}</span>
      <span style="margin-left: 20px">已核销金额：¥{{ totalCurrentSettle.toFixed(2) }}</span>
    </div>
  </div>

  <!-- 修改确定按钮事件处理 -->
  <el-button 
    type="primary" 
    @click="confirmSelection"
    :disabled="totalCurrentSettle >= maxSettleAmount"
  >
    确定（剩余可核销：¥{{ (maxSettleAmount - totalCurrentSettle).toFixed(2) }}）
  </el-button>


    <div class="total-summary">
      <div class="total-label">收款合计</div>
      <div class="total-amount">{{ formatPaymentTotal }}</div>
    </div>
  </div>

  <!-- 源单信息表格 -->
  <div class="source-info">
    <div class="toolbar">
      <el-button type="primary" @click="selectSourceOrder">选择源单</el-button>
      <el-button type="warning" @click="autoSettled">自动核销</el-button>
    </div>

    <el-table :data="sourceOrders" border style="width: 100%">
      <el-table-column label="源单日期" align="center" width="120">
        <template #default="scope">{{ scope.row.orderDate }}</template>
      </el-table-column>
      
      <el-table-column label="源单类型" align="center" width="120">
        <template #default="scope">{{ scope.row.orderType }}</template>
      </el-table-column>

      <el-table-column label="源单编号" align="center" width="180">
        <template #default="scope">{{ scope.row.orderCode }}</template>
      </el-table-column>

      <el-table-column label="客户名称" align="center" width="150">
        <template #default="scope">{{ scope.row.customerName }}</template>
      </el-table-column>

       <el-table-column label="应收金额" align="center" width="120">
        <template #default="scope">¥{{ scope.row.totalAmount.toFixed(2) }}</template>
      </el-table-column> 

      <el-table-column label="已核销金额" align="center" width="120">
        <template #default="scope">¥{{ scope.row.settledAmount.toFixed(2) }}</template>
      </el-table-column>

      <el-table-column label="未核销金额" align="center" width="120">
        <template #default="scope">¥{{ (scope.row.totalAmount - scope.row.settledAmount).toFixed(2) }}</template>
      </el-table-column>

      <el-table-column label="本次核销" align="center" width="150">
        <template #default="scope">
          <el-input-number
            v-model="scope.row.currentSettle" 
            :min="0"
            :max="scope.row.totalAmount - scope.row.settledAmount"
            :precision="2"
            controls-position="right"
            style="width: 120px"
          />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="80">
        <template #default="scope">
          <el-button link type="danger" @click="removeSourceOrder(scope.row)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
 
  
   <el-dialog
   v-model="dialogVisible"
   title="销售出库单"
   width="80%"
   top="5vh"
 >
   <!-- 查询条件区域 -->
   <div class="dialog-header">
     <el-input 
       v-model="searchForm.code" 
       placeholder="请输入单据编号" 
       style="width: 240px;margin-right: 15px"
     />
     <span class="date-label">单据日期：</span>
     <el-date-picker
       v-model="searchForm.startDate"
       type="date"
       placeholder="开始日期"
       value-format="YYYY-MM-DD"
       style="width: 160px"
     />
     <span class="date-separator">~</span>
     <el-date-picker
       v-model="searchForm.endDate"
       type="date"
       placeholder="结束日期"
       value-format="YYYY-MM-DD"
       style="width: 160px;margin-right: 15px"
     />
     <el-button type="primary" icon="Search" @click="searchSalesOut">查询</el-button>
     <el-button icon="Refresh" @click="resetSearch">重置</el-button>
     <el-button icon="ArrowDown">展开</el-button>
   </div>
 
   <!-- 选择状态提示 -->
   <div class="selected-info">
     <span>已选择{{ selectedCount }}项</span>
     <el-button link type="primary" @click="clearSelection">清空</el-button>
   </div>
 
   <!-- 表格区域 -->
   <el-table 
     :data="salesOutList" 
     border 
     height="60vh"
     @selection-change="handleSelectionChange"
     
   >
     <el-table-column type="selection" width="55" align="center" />
     <el-table-column prop="code" label="单据编号" width="180" />
     <el-table-column prop="orderDate" label="单据日期" width="120" />
     <el-table-column prop="bjName" label="单据主题" width="200" />
     <el-table-column prop="customerName" label="客户" width="120" />
     <el-table-column prop="deptName" label="业务部门" width="120" />
     <el-table-column prop="storeManName" label="库管员" width="120" />
     <el-table-column prop="closed" label="已关闭" width="100" align="center">
       <template #default="scope">
         <el-tag :type="scope.row.closed ? 'danger' : 'success'" size="small">
           {{ scope.row.closed ? '是' : '否' }}
         </el-tag>
       </template>
     </el-table-column>
   </el-table>
 
   <!-- 分页及操作按钮 -->
   <div class="dialog-footer">
      <!-- 分页组件 -->
      <div class="pagination-wrapper">
             <el-pagination
                 background
                 layout="prev, pager, next"
                 :total="totalItems"
                 :page-size="PopupsPageSize"
                 :current-page="PopupsPageNo"
                 @current-change="handlePageChange"
             />
         </div>
     <div class="action-buttons">
       <el-button @click="dialogVisible = false">关闭</el-button>
       <el-button type="primary" @click="confirmSelection">确定</el-button>
     </div>
   </div>
 </el-dialog>
 
 
 
 </template>
 
 
 <script setup lang="ts">
 import { ref, reactive,withKeys ,watch,computed, onMounted} from 'vue';
 import BasicInformation from '@/public-view/BasicInformation.vue';
 import type {ComponentSize, FormInstance, FormRules} from 'element-plus'
 import {ElInput, ElAutoResizer, ElTableV2} from 'element-plus'
 import type {FunctionalComponent} from 'vue'
 import type {Column, InputInstance} from 'element-plus'
 import { useRouter,useRoute } from 'vue-router';
 import type { Customer } from '@/types/public-xs/Customer';
 import axios from 'axios';
 import { ElMessageBox, ElMessage } from 'element-plus'
 import type { SalesCollection,SalesCollectiondetail,SalesOut,SalesOutDetail} from '@/types/public-xs/salesDocuments';
 import type { PaymentMethod,CwOtherIncomePayname } from '@/types/public-xs/CwOtherIncome';
 import type { OutStoreOrder } from '@/types/kc/outStore';
 import type { User,Department } from '@/types/rs/User';
 import request from '@/util/request'
import type { PayAccount } from '@/types/cw/Public';

 let docCode=ref('')
 let sourceSheet=ref('')
 let title=ref('销售收款单')
 let pageNo=ref(1)
 let pageSize=ref(5)
 let allPage=ref(0)
 let router=useRouter()

 //销售收款单
let details = ref<SalesCollectiondetail[]>([])
let salesCollection=ref<SalesCollection>({
    id: 0,
    docCode: 'string',
    docDate:new Date,
    cid: null,
    uid: null,
    collectionAmount: 0,//收款金额
    sourceSheet:'',
    status: 0,
    notes: '',
    createBy: 'admin',
    createTime:new Date,
    updateBy: 'admin',
    updateTime:new Date,
    isDelete: 0,
    did: null,
    settledTotalAmount: 0,//收款核销总金额
    details:details.value,
    typeId:15
})


 //商品查询条件
 const queryConditions = reactive({
   combine: '',
   kid: ''
 })
const rules = reactive<FormRules>({
  cid: [
    { required: true, message: '必须选择客户', trigger: ['blur', 'change'] },
    { type: 'number', message: '客户ID必须为数值类型' }
  ],
  docDate: [
  { 
    required: true, 
    message: '必须选择单据日期', 
    trigger: 'change',
    validator: (_, value) => {
      if (!value) return false
      
      // 创建只包含日期的对象（忽略时间）
      const selected = new Date(value)
      const selectedDateOnly = new Date(
        selected.getFullYear(),
        selected.getMonth(),
        selected.getDate()
      )
      
      const today = new Date()
      const todayDateOnly = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate()
      )
      
      return selectedDateOnly > todayDateOnly 
        ? '不能选择未来日期' 
        : true
    }
  }
],
  uid: [
    { required: true, message: '必须选择业务员', trigger: 'change' },
    { type: 'number', message: '业务员ID必须为数值' }
  ],
  did: [
    { required: true, message: '必须选择部门', trigger: 'change' }
  ],
  notes: [
    { max: 200, message: '备注不能超过200字符', trigger: 'blur' }
  ]
})
// 收款表格规则
const tableRules = reactive({
  accountName: [{
    required: true,
    message: '必须选择收款账户',
    trigger: ['blur', 'change']
  }],
  paymentMethod: [{
    required: true,
    message: '必须选择收款方式',
    trigger: ['blur', 'change']
  }],
  amount: [
    { required: true, message: '必须填写金额' },
    { 
      type: 'number',
      min: 0.01,
      message: '金额需大于0',
      trigger: ['blur', 'change']
    }
  ],
  fee: [
    { 
      validator: (_:any, val:number, row:any) => val <= row.amount,
      message: '手续费不能超过收款金额',
      trigger: ['blur', 'change']
    }
  ],
  transactionNo: [
    { 
      validator: (_:any, val:number, row:any) => 
        row.paymentMethod === 2 && !val ? '银行转账必须填写交易号' : true, // 假设2是银行转账
      trigger: ['blur', 'change']
    }
  ]
})



 const disabledDate = (time: Date) => {
     return time.getTime() > Date.now()
 }
 // 修改handleAction方法
 const handleAction = (action:string) => {
   switch(action) {
     case 'choose':
       if (!salesCollection.value.cid) {
         ElMessage.warning('请先选择客户')
         return
       }
       dialogVisible.value = true
        // 自动触发数据加载
        searchSalesOut()
       break
     case 'save-add':
     insertSalesClo()
       break;
     case 'history':
       router.push('/home/SalesCollectionInfo')
       break;
   }
 }

 const mainActions = ref([
   { 
     name: 'save', 
     label: '保存', 
     type: 'primary',
     icon: 'DocumentAdd'
   },
   {
     name: 'save-add',
     label: '保存新增',
     disabled: false
   },
   {
     name: 'audit',
     label: '审核',
     hidden: false
   },
   {
     name: 'choose',
     label: '选择源单',
     hidden: false
   },
   {
     name: 'history',
     label: '历史单据',
     badge: 3 // 角标数字
   }
 ])

  //获取到付款方式的方法
 let payIdList=ref<PaymentMethod[]>([])
 let selectpayId=async()=>{
  let response=await request.post("/cw/PaymentMethodController/selectPaymentMethod")
   payIdList.value=response.data.data
   console.log(payIdList.value)
 }
selectpayId()

 
 //访问方法并获取单据编号
 let getDocCode=async()=>{
   let response=await request.post('/xs/counter/addCode',{docType:'XSSKD'})
   docCode.value=response.data.data
   salesCollection.value.docCode=docCode.value
 }
 
 onMounted(async () => {
   await getDocCode()
 })
 
 // todo
 const generateUUID = () => {
     return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
     const r = (Math.random() * 16) | 0
     const v = c === 'x' ? r : (r & 0x3) | 0x8
     return v.toString(16)
   })
 }
 //动态加载客户
let customerList = ref<Customer[]>([])
let selectCustomer = async () => {
    let response = await request.post('/basic/Customer/selectAllCustomer')
    customerList.value = response.data.data
    console.log(customerList.value)

}
selectCustomer()


//查询业务员的方法
let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await  request.post('/per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

let deptList=ref<Department[]>([])
let selectDept=async()=>{
  let response=await  request.post('/per/dept/getAll')
  deptList.value=response.data.data
  console.log(deptList.value)
}
selectDept()

let payAccountList = ref<PayAccount[]>([])
let  selectAllBankAccount=async()=>{
  let accountRes = await request.post("basic/Account/selectAllAccount")
  payAccountList.value = accountRes.data.data
}
selectAllBankAccount()



 
 const tableData = ref([{ 
   id: generateUUID(), 
   goodId:0,
   code: '',
   name:'',
   quantity: 1,
   actualPrice: 0,
   returnReason: '',
   tax: 13,
   taxIncludedPrice: 0,
   stock:100,
   unit: '件',
   kname:'测试',
   returnQuantity:0
 }])
 

 const newSelectedRows = ref<any[]>([])
 
 // 处理选中行变化
 const newHHandleSelectionChange = (selection: any[]) => {
   newSelectedRows.value = selection
 }
 
 // 删除选中行方法（添加确认对话框）
 const deleteSelectedRows = async () => {
   if (newSelectedRows.value.length === 0) {
     ElMessage.warning('请先选择要删除的行')
     return
   }
 
   try {
     await ElMessageBox.confirm(
       `确定要删除选中的 ${newSelectedRows.value.length} 行吗？`,
       '删除确认',
       {
         confirmButtonText: '确定',
         cancelButtonText: '取消',
         type: 'warning'
       }
     )
     // 通过ID过滤实现删除
     const selectedIds = new Set(newSelectedRows.value.map(row => row.id))
     tableData.value = tableData.value.filter(row => !selectedIds.has(row.id))
     ElMessage.success('删除成功')
   } catch (error) {
     ElMessage.info('已取消删除')
   }
 }
 
 
 //价格校验
 const validatePrice = (row:any) => {
   row.actualPrice = row.actualPrice.replace(/[^\d.]/g, '')
 }
 

 // 显示历史报价
 const showHistory = (row:any) => {
   console.log('显示历史报价:', row.goodsCode)
   // 实际应调用API获取历史数据
 }
 //格式化金额显示
 const totalAmount = computed(() => {
   return tableData.value.reduce((sum, row) => {
     const price = Number(row.actualPrice) || 0
     const qty = Number(row.returnQuantity) || 0 // 关键修改点
     return sum + (price * qty)
   }, 0)
 })
 const formatTotal = computed(() => {
   return `¥${totalAmount.value.toFixed(2)}`
 })
 let PopupsPageNo=ref(1)
 let PopupsPageSize=ref(10) 
 const selectedCount = ref(0)
 const totalItems = ref(0)
 const dialogVisible = ref(false)
 const currentSelected =ref<OutStoreOrder|null>()
 const selectedRows =ref<OutStoreOrder[]>([])
 const searchForm = reactive({
     code: '',
   startDate: '',
   endDate: ''
 })
 // 表格选择处理
 const handleSelectionChange = (selection:any) => {
   selectedRows.value = selection
   selectedCount.value = selection.length
   if (selection.length > 0) {
     currentSelected.value = selection[0]
   } else {
     currentSelected.value = null
   }
 }
 const clearSelection = () => {
 
 }
 
 //分页方法
 let handlePageChange=()=>{
 
 }
 let salesOutList=ref<SalesOut[]>([])
 // 获取源单数据
 const searchSalesOut = async () => {
   try {
     const params = {
       code: searchForm.code,
       startDate: searchForm.startDate,
       endDate: searchForm.endDate,
       pageNo: PopupsPageNo.value,
       pageSize: PopupsPageSize.value,
       cid:salesCollection.value.cid,
       typeId:6,
       status:3
     }
     const res = await request.post('/kc/outStore/getOutStoreList', params)
     salesOutList.value = res.data.data.list
     console.log("出库单数据",  salesOutList.value)
     totalItems.value = res.data.data.total
   } catch (error) {
     console.error('查询失败:', error)
   }
 }
 const resetSearch = () => {
   searchForm.code = ''
   searchForm.startDate = ''
   searchForm.endDate = ''
   searchSalesOut()
 }
 
 const confirmSelection = async() => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条出库单')
    return
  }

  const newSourceOrders = selectedRows.value.map(row => ({
  orderId: row.id,
  orderDate: row.createDate,
  orderType: '销售出库单', // 根据类型值转换文本
  orderCode: row.code,
  customerName: customerList.value.find(c => c.id === row.cid)?.name,
  totalAmount: row.outStoreSumPrice,
  settledAmount: row.collectionAmount, // 调用接口获取已核销金额
  currentSettle: 0 // 初始化本次核销金额 


}));
  console.log("查看总金额",newSourceOrders)
  
  const existingIds = new Set(sourceOrders.value.map(o => o.orderId))
  const validOrders = newSourceOrders.filter(o => !existingIds.has(o.orderId))
 
  // 添加新订单
 sourceOrders.value = [...sourceOrders.value, ...validOrders]
  
  // 关闭对话框并重置选择
  dialogVisible.value = false
  selectedRows.value = []
  selectedCount.value = 0
  ElMessage.success(`成功添加${validOrders.length}条源单`)
  
 } 

 const generateDetails = () => {
  return paymentAccounts.value.map(payment => ({
    payId: payment.payId,  // 绑定支付方式ID
    accountId: payment.accountName,  // 绑定账户ID
    id: 0, // 生成唯一标识
    collectionCode: salesCollection.value.docCode, // 关联主单编号
    collectionAmount: payment.amount, // 关键修改点：映射核销金额
    discountAmount: '0.00', // 默认折扣金额
    notes: `核销源单 ${payment}`,
    createTime: new Date(),
    createBy: 'admin',
    updateTime: new Date(),
    updateBy: 'admin',
    isDelete:0,
    fee:payment.fee
  })) as SalesCollectiondetail[];
};
 
                     
 const paymentAccounts = ref([
  {
    id: 1,
    accountName: 1,
    paymentMethod:1,
    amount: 0,
    fee: 0,
    transactionNo: '',
    notes: '',
    account_id: 0 , 
    payId: 1 
  }
])

const bankAccounts = ref([
  { value: 1, label: '招商银行（尾号8899）' },
  { value: 2, label: '工商银行（尾号5566）' }
])

// 新增源单信息相关数据
const sourceOrders = ref<any[]>([])
const sourceDialogVisible = ref(false)

// 计算属性
const formatPaymentTotal = computed(() => {
  const total = paymentAccounts.value.reduce(
    (sum, row) => sum + Number(row.amount) - Number(row.fee),
    0
  )
  return `¥${total.toFixed(2)}`
})



// 新增方法
const selectSourceOrder = () => {
  sourceDialogVisible.value = true
  // 这里可以调用加载源单数据的方法
}

const autoSettled = async () => {
  try {
    const netAmount = netCollectionAmount.value
    if (netAmount <= 0) {
      ElMessage.warning('请先填写有效的收款金额')
      return
    }

    // 计算可分配总额
    let remaining = netAmount
    sourceOrders.value = sourceOrders.value.map(order => {
      const max = order.totalAmount - order.settledAmount
      const allocatable = Math.min(max, remaining)
      order.currentSettle = allocatable
      remaining -= allocatable
      return order
    })

    if (remaining > 0) {
      ElMessage.warning(`自动核销后仍有 ¥${remaining.toFixed(2)} 未分配`)
    }
  } catch (error:any) {
    ElMessage.error('自动核销失败：' + error.message)
  }
}

const removeSourceOrder = (row: any) => {
  sourceOrders.value = sourceOrders.value.filter(item => item.orderId !== row.orderId)
}

const totalSettledAmount = computed(() => {
  return sourceOrders.value.reduce((sum, order) => 
    sum + (order.currentSettle || 0), 0)
});

// 监听器更新主单收款金额
watch(totalSettledAmount, (newVal) => {
  salesCollection.value.collectionAmount = newVal;
});
const validateSettlement = () => {
  if (netCollectionAmount.value > maxSettleAmount.value) {
    ElMessage.error(`收款金额不可超过可核销总额 ¥${maxSettleAmount.value.toFixed(2)}`)
    return false
  }
  
  // 规则2：核销总金额必须等于净收款金额
  if (Math.abs(totalCurrentSettle.value - netCollectionAmount.value) > 0.01) {
    ElMessage.error('核销总金额与净收款金额不匹配')
    return false
  }


  return sourceOrders.value.every(order => {
    const maxAmount = order.totalAmount - order.settledAmount;
    return order.currentSettle > 0 && order.currentSettle <= maxAmount;
  });
};
const maxSettleAmount = computed(() => {
  return sourceOrders.value.reduce((sum, order) => {
    return sum + (order.totalAmount - order.settledAmount)
  }, 0)
})



// 计算实际可用收款金额（总收款金额 - 总手续费）
const netCollectionAmount = computed(() => {
  return paymentAccounts.value.reduce((sum, row) => 
    sum + (Number(row.amount) || 0) - (Number(row.fee) || 0)
  , 0)
})

// 计算当前核销总金额
const totalCurrentSettle = computed(() => {
  return sourceOrders.value.reduce((sum, order) => 
    sum + (Number(order.currentSettle) || 0)
  , 0)
})

watch(netCollectionAmount, (newVal) => {
  // 当净收款金额变化时更新所有源单的核销金额
  sourceOrders.value.forEach(order => {
    const maxAvailable = order.totalAmount - order.settledAmount
    order.currentSettle = Math.min(newVal, maxAvailable)
  })
})

const handlePaymentChange = (row: any) => {


  // 计算当前行净金额
  const netAmount = Number(row.amount) - Number(row.fee || 0)
  
  // 自动分配核销金额（按比例分配）
  const totalSettlable = sourceOrders.value.reduce((sum, o) => 
    sum + (o.totalAmount - o.settledAmount), 0)

      if (totalSettlable <= 0) {
  ElMessage.warning('无可核销源单')
  return
}

if (netAmount > totalSettlable) {
  ElMessage.error('收款金额超过可核销总额')
  row.amount = totalSettlable
}
  
  sourceOrders.value = sourceOrders.value.map(order => {
    const orderMax = order.totalAmount - order.settledAmount
    const ratio = orderMax / totalSettlable
    order.currentSettle = parseFloat((netAmount * ratio).toFixed(2))
    return order
  })
}

const formRef = ref<FormInstance>()
const validateAll = async () => {
  try {
    // 1. 校验主表单
    await formRef.value?.validate()
    
    // 2. 校验收款表格
    const paymentValidate = paymentAccounts.value.map((_, index) => 
      formRef.value?.validateField([
        `paymentAccounts.${index}.accountName`,
        `paymentAccounts.${index}.paymentMethod`,
        `paymentAccounts.${index}.amount`
      ])
    )
    await Promise.all(paymentValidate)

    // 3. 校验源单核销
    const sourceValidate = sourceOrders.value.map((_, index) =>
      formRef.value?.validateField(
        `sourceOrders.${index}.currentSettle`
      )
    )
    await Promise.all(sourceValidate)

    // 4. 业务规则校验
    if (netCollectionAmount.value <= 0) {
      throw new Error('有效收款金额需大于0')
    }
    
    if (totalCurrentSettle.value.toFixed(2) !== netCollectionAmount.value.toFixed(2)) {
      throw new Error('核销总金额需等于净收款金额')
    }

    return true
  } catch (error) {
    ElMessage.error('存在未通过校验的字段')
    return false
  }
}
 





 //点击新增后新增收款单
 let insertSalesClo =async()=>{ 
  if (!validateSettlement()) {
    ElMessage.error('存在非法销额度');
    return;
  }
   if (!await validateAll()) return
  // 构造明细数据
  const details = generateDetails()
   // 获取唯一源单信息
  const sourceOrder = sourceOrders.value[0]
  // 设置主表源单字段
  salesCollection.value.sourceSheet = sourceOrder.orderCode
  salesCollection.value.collectionAmount = totalSettledAmount.value;
  salesCollection.value.settledTotalAmount = totalSettledAmount.value;
  // 更新主单收款总额
  salesCollection.value.collectionAmount = totalSettledAmount.value;
    let response=await request.post("/cw/SalesCollectionController/insertSalesCollection",{
      salesCollection:salesCollection.value,
      details:details
    })

    if(response.data.code==200){
      ElMessage.success("收款成功")
      router.push("/home/salesCollectionInfo")
    }else{
      ElMessage.error("收款失败")
    }
 }
 
 </script>
 
 
 <style scoped>
 .el-row {
     margin-bottom: 20px;
 }
 
 .el-row:last-child {
     margin-bottom: 0;
 }
 
 .el-col {
     border-radius: 4px;
 }
 
 .grid-content {
     border-radius: 4px;
     min-height: 36px;
 }
 .required-label::after {
   content: "*";
   color: #f56c6c;
   margin-left: 4px;
 }
 
 .goods-table {
   margin-top: 20px;
 }
 
 .toolbar {
   margin-bottom: 15px;
   padding: 10px;
   background: #f5f7fa;
   border-radius: 4px;
 }
 
 .el-table :deep(.el-input__inner) {
   text-align: center;
 }
 .total-summary {
   background: #fff8dc; /* 浅黄色背景 */
   padding: 12px 20px;
   display: flex;
   justify-content: flex-end;
   border: 1px solid #ebeef5;
   border-top: none;
 }
 
 .total-label {
   font-weight: 600;
   color: #606266;
   margin-right: 30px;
 }
 
 .total-amount {
   color: #f56c6c;
   min-width: 120px;
   text-align: right;
   font-family: Arial, sans-serif;
 }
 .pagination-wrapper {
     margin-top: 16px;
     display: flex;
     justify-content: flex-end;
 }
 .dialog-header {
   display: flex;
   align-items: center;
   margin-bottom: 15px;
   flex-wrap: wrap;
   gap: 10px;
 }
 
 .date-label {
   color: #606266;
   margin: 0 10px;
 }
 
 .date-separator {
   margin: 0 8px;
   color: #c0c4cc;
 }
 
 .selected-info {
   margin: 12px 0;
   display: flex;
   align-items: center;
   gap: 10px;
   color: #606266;
 }
 
 .dialog-footer {
   display: flex;
   justify-content: space-between;
   align-items: center;
   margin-top: 15px;
 }
 
 .pagination-info {
   color: #606266;
 }
 
 .action-buttons {
   display: flex;
   gap: 15px;
 }
 
 :deep(.el-dialog__header) {
   border-bottom: 1px solid #ebeef5;
 }

 .collection-info {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.source-info {
  margin-top: 20px;
  border-top: 2px solid #ebeef5;
  padding-top: 15px;
}

.toolbar {
  margin-bottom: 15px;
}

.total-summary {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 15px;
  padding: 10px;
  background: #f4f4f5;
  border-radius: 4px;
}

.total-label {
  font-weight: 600;
  margin-right: 20px;
}

.total-amount {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}
.validation-info {
  margin: 15px 0;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
}

.amount-summary {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

.el-alert {
  margin-bottom: 10px;
}
/* 错误状态指示 */
:deep(.el-form-item.is-error) {
  .el-input__inner, .el-select__wrapper {
    border-color: #f56c6c;
    box-shadow: 0 0 3px rgba(245,108,108,.3);
  }
  
  .el-form-item__error {
    font-size: 12px;
    padding-top: 4px;
  }
}

/* 超额提示样式 */
.validation-info {
  transition: all 0.3s;
  &.exceed {
    background: #fff2f0;
    border: 1px solid #ffccc7;
  }
}

 </style>







